'use strict';

module.exports = () => {
  return async (ctx, next) => {
    const fs = require('fs');
    const path = require('path');
    const { app, socket, packet } = ctx;
    const nsp = app.io.of('/');
    const query = socket.handshake.query;
    // 用户信息
    const { room, userId } = query;
    const { userName } = app.jwt.verify(userId);

    const toId = await app.redis.get(packet[1].to + '_wsId');


    if (packet[0] === 'videoChat') {
      console.log(packet[1].stream);
    } else {

      if (packet[1].msg.type === 'rec') {
        // const msg = Buffer.from(packet[1].msg.blob);
        const name = Date.now() + '.mp3';
        fs.writeFileSync(path.resolve(__dirname, '../../public/rec/' + name), packet[1].msg.blob, err => {
          console.log(err);
        });
        nsp.to(toId).emit(packet[1].to, {
          from: userName,
          msg: {
            type: 'rec',
            blob: 'public/rec/' + name,
          },
        });
      } else if (packet[1].msg.type === 'image') {
        nsp.to(toId).emit(packet[1].to, {
          from: userName,
          msg: {
            type: 'image',
            blob: packet[1].msg.blob,
          },
        });
      } else if (packet[1].msg.type === 'video') {
        nsp.to(toId).emit(packet[1].to, {
          from: userName,
          msg: {
            type: 'video',
            blob: packet[1].msg.blob,
          },
        });
      } else if (packet[1].msg.type === 'icon') {
        nsp.to(toId).emit(packet[1].to, {
          from: userName,
          msg: {
            type: 'icon',
            blob: packet[1].msg.blob,
          },
        });
      } else {
        nsp.to(toId).emit(packet[1].to, {
          from: userName,
          msg: packet[1].msg,
        });
      }
    }


    await next();
    console.log('packet response!');
  };
};
